package org.sunrise.game.client.client;

import io.netty.channel.Channel;
import lombok.Getter;
import lombok.Setter;
import okhttp3.OkHttpClient;
import okhttp3.Request;
import okhttp3.Response;
import org.sunrise.game.client.gen.TopicProto;
import org.sunrise.game.common.log.LogCore;
import org.sunrise.game.common.network.message.MessageType;
import org.sunrise.game.common.network.message.SocketMessage;

import java.io.IOException;
import java.util.concurrent.TimeUnit;

@Getter
@Setter
public abstract class SocketClient {
    protected boolean connectSuccess = false;
    protected String uid;
    protected String humanId;
    protected int connectId;
    protected Channel channel;
    protected OkHttpClient httpClient;
    protected boolean startSend = false;
    protected long loginStartTime = 0L;
    protected long pingStartTime = 0L;
    protected int sendCount = 0;
    protected int recvCount = 0;

    public void initHttp() {
        // 创建 OkHttpClient 实例
        httpClient = new OkHttpClient.Builder()
                .connectTimeout(10, TimeUnit.SECONDS) // 设置连接超时时间
                .readTimeout(10, TimeUnit.SECONDS) // 设置读取超时时间
                .build();
    }

    public String curl(String url) {
        Request request = new Request.Builder()
                .url(url)
                .build();

        try (Response response = httpClient.newCall(request).execute()) {
            if (!response.isSuccessful()) {
                return null;
            }
            // 读取响应内容
            if (response.body() == null) {
                return null;
            }
            return response.body().string();
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public abstract void connect(String host, int port);

    public void sendMsg(TopicProto.MBasePacketData msg) {
        channel.writeAndFlush(new SocketMessage(MessageType.biz, msg.toByteArray()));
        LogCore.Client.debug("sendMsg, {} {} {}", msg.getPacketType(), msg.getPacketId(), msg.getPacketData());
    }
}
